﻿namespace Vboot.Core.Module.Ass;

public class AssCogeTableService : BaseMainService<AssCogeTable>, ITransient
{
    public async Task<AssCogeTable> FindOne(string id)
    {
        var main = await SingleAsync(id);
        if (main != null)
        {
            main.fields = await repo.Context.Queryable<AssCogeField>()
                .Where(it => it.tabid.Equals(main.id))
                .OrderBy(it=>it.ornum).ToListAsync();
        }
        return main;
    }
    
    public async Task Insertx(AssCogeTable table)
    {
        if (string.IsNullOrEmpty(table.id))
        {
            table.id = YitIdHelper.NextId() + "";
        }
        table.crmid = XuserUtil.getUserId();
        table.crtim = DateTime.Now;
        table.avtag = true;

        await repo.Context.Insertable(table)
            .AddSubList(it => it.fields.First().tabid)
            .ExecuteCommandAsync();
    }
    
    public async Task Updatex(AssCogeTable table)
    {
        table.uptim = DateTime.Now;
        table.upmid = XuserUtil.getUserId();
        await repo.Context.Updateable(table).ExecuteCommandAsync();

        //比对数据库中的option,插入页面上新增的，更新页面上修改的，删除页面上删除的
        List<AssCogeField> list = await repo.Context.Queryable<AssCogeField>()
            .Where(t => t.tabid == table.id).ToListAsync();
        List<AssCogeField> insertList = new List<AssCogeField>();
        List<AssCogeField> updateList = new List<AssCogeField>();
        List<AssCogeField> deleteList = new List<AssCogeField>();
        for (int i = 0; i < list.Count; i++)
        {
            bool flag = false;
            for (int j = 0; j < table.fields.Count; j++)
            {
                if (table.fields[j].id == list[i].id)
                {
                    flag = true;
                    updateList.Add(table.fields[j]); //找到相同的则更新
                    break;
                }
            }

            if (!flag)
            {
                deleteList.Add(list[i]);
            }
        }

        for (int j = 0; j < table.fields.Count; j++)
        {
            bool flag = false;
            for (int i = 0; i < list.Count; i++)
            {
                if (table.fields[j].id == list[i].id)
                {
                    flag = true;
                    break;
                }
            }

            if (!flag)
            {
                insertList.Add(table.fields[j]);
            }
        }

        await repo.Context.Deleteable(deleteList).ExecuteCommandAsync();
        await repo.Context.Updateable(updateList).ExecuteCommandAsync();
        await repo.Context.Insertable(insertList).ExecuteCommandAsync();
    }
    
    
    public AssCogeTableService(SqlSugarRepository<AssCogeTable> repo)
    {
        base.repo = repo;
    }
}